<?php
// +----------------------------------------------------------------------
// | 小说系统 [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\common\controller\Admin;
use think\Db;

class User2 extends Admin {

	/**
	 * 用户管理首页
	 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
	 */
	public function index() {
		$map   = array();
		$list  = db("User")->where($map)->field(true)->order('id asc,id asc')->column('*', 'id');
		int_to_string($list, array('status' => array(1 => '正常', 0 => '禁用')));

		if (!empty($list)) {
			$tree = new \com\Tree();
			$list = $tree->toFormatTree($list);
		}
		// 记录当前列表页的cookie
		Cookie('__forward__', $_SERVER['REQUEST_URI']);

		$this->setMeta('菜单列表');
		$this->assign('list', $list);
		return $this->fetch();
	}

	/**
	 * 添加用户
	 * @author netlife <40150501@qq.com>
	 */
	public function add() {
		$model = \think\Loader::model('User');
		if (IS_POST) {
			$data = $this->request->param();
			//创建注册用户
            $email = rand_string(8).'@qq.com';
			$result = $model->register($data['username'], $data['password'], $data['repassword'], $email, false);
			if ($result) {
				return $this->success('添加成功！', url('admin/user/index'));
			} else {
				return $this->error($model->getError());
			}
		} else {
			$data = array(
				'keyList' => $model->addfield,
				'grouplist' =>$this->groups(),
			);
			$this->assign($data);
			$this->setMeta("添加员工");
            return $this->fetch('add');
		}
	}

	/**
	 * 修改昵称初始化
	 * @author huajie <banhuajie@163.com>
	 */
	public function edit() {
		$model = model('User');
		if (IS_POST) {
			$data = $this->request->post();
            if(array_key_exists("mobile", $data)){
                if($data['mobile']==''||$data['mobile']=='0'){
                    unset($data['mobile']);
                }
            }
			$reuslt = $model->editUser($data, true);

			if (false !== $reuslt) {
				return $this->success('修改成功！', url('admin/user/index'));
			} else {
				return $this->error($model->getError(), '');
			}
		} else {
			$info = $this->getUserinfo();
			$info = $info->toArray();
			//var_dump($info);
			$data = array(
				'info'    => $info,
				//'keyList' => $model->editfield,
                'grouplist' =>$this->groups(),
			);

			
			$this->assign($data);
			$this->setMeta("编辑信息");
			return $this->fetch('edit');
		}
	}

	public function info() {
		$model = model('User');
		
		$info = $this->getUserinfo();

		$percentage = db('member_extend')->where('uid',$info['uid'])->value('percentage');
		

		$data = array(
			'percentage'    => $percentage,
			'info'    => $info,
			'keyList' => $model->editfield,
		);
		
		$this->assign($data);
		$this->setMeta("个人资料");
		return $this->fetch('user/info');
		
	}

	public function common_userinfo($info) {
		//关注时间
		$userapi = Db::name('member_userapi')->where(['uid'=>$info["uid"]])->find();
		$subscribe_at="";
		$unsubscribe_at="";
		if($userapi){
			$fans = Db::name('wechat_fans')->where(["appid"=>$userapi["appid"],"openid"=>$userapi["wxmpid"]])->cache(true)->field("subscribe_at,unsubscribe_at")->find();
			if(!empty($fans)){
				$subscribe_at=$fans['subscribe_at']?date("Y-m-d",$fans['subscribe_at']):"";
				$unsubscribe_at=$fans['unsubscribe_at']?date("Y-m-d",$fans['unsubscribe_at']):"";
			}
		}
		
		//书币总消耗
		$consumedEgold = db("subscription")->where(["uid"=>$info["uid"],"buytype"=>["in",[2,42]]])->cache(true)->sum("price");
		//阅读书籍量
		$readnum = db("subscription")->where(["uid"=>$info["uid"]])->cache(true)->group("articleid")->count();
		
		//渠道二维码
		$wechat = db('wxmp')->where(['uid'=>$info["agentid"],'id'=>$info["wxmpid"]])->value('wechat');
		if($wechat){
			$qrcode = "http://open.weixin.qq.com/qr/code?username=".trim($wechat);
		}else{
			$qrcode =config('agent_qzgzewm');
		}
		//客服二维码
		$kefu_qrcode = db('wxmp')->where(['uid'=>$info["agentid"],'id'=>$info["wxmpid"]])->value('kefu_qrcode_url');
		if(empty($kefu_qrcode)){
			$kefu_qrcode = db('wxmp')->where('uid',1)->value('kefu_qrcode_url');
		}
		$data = [
			'subscribe_at'    => $subscribe_at,
			'unsubscribe_at'    => $unsubscribe_at,
			'consumedEgold'    => $consumedEgold,
			'readnum'    => $readnum,
			'qrcode'    => $qrcode,
			'kefu_qrcode'    => $kefu_qrcode,
		];
		return $data;
	}
	//前台用户详情
	public function userinfo() {
		$model = model('User');
		$info = $this->getUserinfo();
		
		$commoninfo  = $this->common_userinfo($info);

		$order = db('order')->where(['status'=>1,'is_kouliang'=>0,"uid"=>$info["uid"]])->order("id desc")->paginate(10);
		
		$data = array(
			'order'    =>$order,
			'page' => $order->render(),
			'info'    => $info,
		);
		
		$this->assign($data);
		$this->assign($commoninfo);
		$this->setMeta("员工详情");
		return $this->fetch();
	}
	//用户消费记录
	public function userconsuming() {
		$model = model('User');
		$info = $this->getUserinfo();
		
		$commoninfo  = $this->common_userinfo($info);
		
		$subscription = db('subscription')->where(["uid"=>$info["uid"],"model"=>1])->order("id desc")->paginate(10);


		$data = array(
			'subscription'    =>$subscription,
			'page' => $subscription->render(),
			'info'    => $info,
		);
		$this->assign($data);
		$this->assign($commoninfo);
		$this->setMeta("用户消费记录");
		return $this->fetch();
	}
	//用户阅读记录
	public function userhistory() {
		$model = model('User');
		$info = $this->getUserinfo();
		
		$commoninfo  = $this->common_userinfo($info);

		$historylog = db('history_log')->where(["uid"=>$info["uid"]])->order("articleid desc,`order` desc")->paginate(10);

		$data = array(
			'historylog'    =>$historylog,
			'page' => $historylog->render(),
			'info'    => $info,
		);
		$this->assign($data);
		$this->assign($commoninfo);
		$this->setMeta("用户阅读记录");
		return $this->fetch();
	}
	//用户充值记录
	
	public function userpaylog() {
		
		$model = model('User');
		$info = $this->getUserinfo();
		
		$commoninfo  = $this->common_userinfo($info);

		$order = db('order')->where(['status'=>1,'is_kouliang'=>0,"uid"=>$info["uid"]])->order("id desc")->paginate(10);
		
		$data = array(
			'order'    =>$order,
			'page' => $order->render(),
			'info'    => $info,
		);
		
		$this->assign($data);
		$this->assign($commoninfo);
		$this->setMeta("用户阅读记录");
		return $this->fetch();
	}

	public function userdelhistory() {
		


		return $this->fetch();
	}

	/**
	 * del
	 * @author colin <colin@tensent.cn>
	 */
	public function del($id) {
		
		$uid = array('IN', is_array($id) ? implode(',', $id) : $id);
		
		if(in_array(1,$uid)){
			return $this->error("超级管理员账号不能删除！");
		}
		//账户有绑定微信公众号不能删除
        $wxmpinfo = db('wxmp')->where('uid','=',$id)->count();
		if($wxmpinfo>0){
            return $this->error("该账户有绑定微信公众号,不能删除！");
        }
		//获取用户信息
		$find = $this->getUserinfo($uid);
		model('User')->where(array('uid' => $uid))->delete();
		db('MemberUserapi')->where(array('uid' => $uid))->delete();
		return $this->success('删除用户成功！');
	}

    /**
     * 修改昵称初始化
     * @author huajie <banhuajie@163.com>
     */
    public function agentedit() {
        $model = model('User');
        if (IS_POST) {
            $data = $this->request->post();

            $reuslt = $model->editUser($data, true);

            if (false !== $reuslt) {
                return $this->success('修改成功！', url('admin/user/agent'));
            } else {
                return $this->error($model->getError(), '');
            }
        } else {
            $info = $this->getUserinfo();

            $data = array(
                'info'    => $info,
                'keyList' => $model->editfield,
            );

            $this->assign($data);
            $this->setMeta("编辑员工");
            return $this->fetch('agentedit');
        }
    }

	public function auth() {
		$access = model('AuthGroupAccess');
		$group  = model('AuthGroup');
		
		if (IS_POST) {
			$uid = input('uid', '', 'trim,intval');
			$access->where(array('uid' => $uid))->delete();
			$group_type = config('user_group_type');
			foreach ($group_type as $key => $value) {
				$group_id = input($key, '', 'trim,intval');
				if ($group_id) {
					$add = array(
						'uid'      => $uid,
						'group_id' => $group_id,
					);
					$access->save($add);
					db('member')->where('uid='.$uid)->setField('group',$group_id);
				}
			}
			return $this->success("设置成功！",url('admin/user/index'));
		} else {
			$uid  = input('id', '', 'trim,intval');
			$row  = $group::select();
			$auth = $access::where(array('uid' => $uid))->select();
			
			$auth_list = array();
			foreach ($auth as $key => $value) {
				$auth_list[] = $value['group_id'];
			}
			
			foreach ($row as $key => $value) {
				if($value['id']!=3&&$value['id']!=4){
					$list[$value['module']][] = $value;
				}
				
			}

			//获取权限节点
            $row = db('AuthRule')->where('module','=','admin')->order('id desc')->select();
            $rolelist = array();
            foreach ($row as $key => $value) {
                $rolelist[$value['group']][] = $value;
            }

			$data = array(
				'uid'       => $uid,
				'auth_list' => $auth_list,
				'list'      => $list,
                'rolelist'  => $rolelist,
			);
			$this->assign($data);
			$this->setMeta("员工权限");
			return $this->fetch();
		}
	}

	/**
	 * 获取某个用户的信息
	 * @var uid 针对状态和删除启用
	 * @var pass 是查询password
	 * @var errormasg 错误提示
	 * @author colin <colin@tensent.cn>
	 */
	private function getUserinfo($uid = null, $pass = null, $errormsg = null) {
		$user = model('User');
		$uid  = $uid ? $uid : input('id');
		//如果无UID则修改当前用户
		$uid        = $uid ? $uid : session('user_auth.uid');
		
		$map['uid'] = $uid;
		if ($pass != null) {
			unset($map);
			$map['password'] = $pass;
		}
		$list = $user::where($map)->find();
		if (!$list) {
			return $this->error($errormsg ? $errormsg : '不存在此用户！');
		}
		return $list;
	}

	/**
	 * 修改昵称提交
	 * @author huajie <banhuajie@163.com>
	 */
	public function submitNickname() {

		//获取参数
		$nickname = input('post.nickname');
		$password = input('post.password');
		if (empty($nickname)) {
			return $this->error('请输入昵称');
		}
		if (empty($password)) {
			return $this->error('请输入密码');
		}

		//密码验证
		$User = new UserApi();
		$uid  = $User->login(UID, $password, 4);
		if ($uid == -2) {
			return $this->error('密码不正确');
		}

		$Member = model('User');
		$data   = $Member->create(array('nickname' => $nickname));
		if (!$data) {
			return $this->error($Member->getError());
		}

		$res = $Member->where(array('uid' => $uid))->save($data);

		if ($res) {
			$user             = session('user_auth');
			$user['username'] = $data['nickname'];
			session('user_auth', $user);
			session('user_auth_sign', data_auth_sign($user));
			return $this->success('修改昵称成功！');
		} else {
			return $this->error('修改昵称失败！');
		}
	}

	/**
	 * 修改密码初始化
	 * @author huajie <banhuajie@163.com>
	 */
	public function editpwd() {
		if (IS_POST) {
			$user = model('User');
			$data = $this->request->post();

			$res = $user->editpw($data);
			if ($res) {
				return $this->success('修改密码成功！');
			} else {
				return $this->error($user->getError());
			}
		} else {
			$this->setMeta('修改密码');
			return $this->fetch();
		}
	}

	/**
	 * 会员状态修改
	 * @author 朱亚杰 <zhuyajie@topthink.net>
	 */
	public function changeStatus($method = null) {
		$id = array_unique((array) input('id', 0));
		if (in_array(config('user_administrator'), $id)) {
			return $this->error("不允许对超级管理员执行该操作!");
		}
		$id = is_array($id) ? implode(',', $id) : $id;
		if (empty($id)) {
			return $this->error('请选择要操作的数据!');
		}
		$map['uid'] = array('in', $id);
		switch (strtolower($method)) {
		case 'forbiduser':
			$this->forbid('Member', $map);
			break;

		case 'resumeuser':
			$this->resume('Member', $map);
			break;

		case 'deleteuser':
			$this->delete('Member', $map);
			break;

		default:
			return $this->error('参数非法');
		}
	}

	/**
      * percentage [阅读币修改]
      *
      * @return type
    **/
	public function setegold() {
		
		if (IS_POST) {
			$uid= input('id');
			$egold = input('post.egold');
			$result = db('member')->where('uid',$uid)->setInc('egold', $egold);
			if ($result) {				
				return $this->success("充值成功！", url('admin/user/index'));
			} else {
				return $this->error($this->model->getError(), url('admin/user/index'));
			}
		} else {
			$this->setMeta("手工充值");
			return $this->fetch();
		}
	}

	/**
      * percentage [阅读币修改]
      *
      * @return type
    **/
	public function setvip() {
		
		if (IS_POST) {
			$uid= input('id');
			$data['is_vip'] = input('post.is_vip');
			if($data['is_vip']==1){
				$data['vip_enddate'] = time()+3600*24*30;
			}elseif($data['is_vip']==2){
				$data['vip_enddate'] = time()+3600*24*90;
			}elseif($data['is_vip']==3){
				$data['vip_enddate'] = time()+3600*24*365;
			}
			$result = db('member')->where('uid',$uid)->update($data);
			if ($result) {				
				return $this->success("开通成功！", url('admin/user/index'));
			} else {
				return $this->error($this->model->getError(), url('admin/user/index'));
			}
		} else {
			$uid= input('id');
			$username = db('member')->where('uid',$uid)->value('username');
			$this->assign('username',$username);
			$this->assign('uid',$uid);
			$this->setMeta("开通包月/包季/包年用户");
			return $this->fetch();
		}
	}

    /**
      * percentage [抽成设置]
      *
      * @return type
    **/
	public function percentage() {
		
		if (IS_POST) {
			$uid= input('id');
			$data['percentage'] = input('post.percentage');

			if(session('user_auth.group') ==3){
				$nowuid = session('user_auth.uid');
				$percentage = db('member_extend')->where(array('uid'=>$nowuid))->value('percentage');
				if($data['percentage']>$percentage){
					return $this->error("您设置的下级分成比列不能高于您与平台的分成比列", url('admin/user/agent'));
				}
			}
			
			$result = db('member_extend')->where('uid',$uid)->update($data);
			if ($result) {				
				return $this->success("添加成功！", url('admin/user/agent'));
			} else {
				return $this->error($this->model->getError(), url('admin/user/agent'));
			}
		} else {
			$uid= input('id');
			$percentage = db('member_extend')->where('uid',$uid)->value('percentage');
			$qudao_percentage = 0;
			if(session('user_auth.group')==3){
				$qudao_percentage = db('member_extend')->where('uid',session('user_auth.uid'))->value('percentage');
			}
			$this->assign('qudao_percentage',$qudao_percentage);
			$this->assign('percentage',$percentage);
			$this->setMeta("抽成设置");
			return $this->fetch();
		}
	}
    /**
      * gathering [修改收款信息]
      *
      * @return type
    **/
	public function gathering() {
		
		if (IS_POST) {
			$data = input();
			$uid= input('id');
			$result = db('member_extend')->where('uid',$uid)->update($data);
			if ($result) {
				if(in_array(session('user_auth.group'),config('cartoon_access'))){
					return $this->success("添加成功！", url('admin/user/agent'));
				}else{
					return $this->success("添加成功！", url('admin/user/gatherinfo'));
					
				}
			} else {
				return $this->error($this->model->getError(), url('admin/user/agent'));
			}
		} else {
			$uid= input('id');
			$info = db('member_extend')->where('uid',$uid)->find();
			$this->assign('info',$info);
			$this->setMeta("收款信息");
			return $this->fetch();
		}
	}

	    /**
      * gathering [收款信息]
      *
      * @return type
    **/
	public function gatherinfo() {
		
		$uid= session('user_auth.uid');
		$info = db('member_extend')->where('uid',$uid)->find();
		
		$this->assign('info',$info);
		$this->assign('uid',$uid);
		$this->setMeta("收款信息");
		return $this->fetch();
		
	}
	
    /**
      * level [等级划分]
      *
      * @return type
    **/
	public function level() {
		
		if (IS_POST) {
			$uid= input('id');
			$data = input();
			$result = db('member_extend')->where('uid',$uid)->update($data);
			if ($result) {				
				return $this->success("添加成功！", url('admin/user/agent'));
			} else {
				return $this->error($this->model->getError(), url('admin/user/agent'));
			}
		} else {
			$uid= input('id');
			$info = db('member_extend')->where('uid',$uid)->find();
			$this->assign('info',$info);
			$this->setMeta("等级划分");
			return $this->fetch();
		}
	}

    /**
      * daili [代理管理]
      *
      * @return type
    **/
	public function agent() {
		$nickname      = input('keyword');
		$level      = input('level');
		$map['m.status'] = array('egt', 0);
		$map['m.group'] = array('in','3,4');
		if (is_numeric($nickname)) {
			$map['m.uid'] = $nickname;
		} else {
			$map['m.nickname|m.username'] = array('like', '%' . (string) $nickname . '%');
		}
		if(session('user_auth.group')!=999){
			$info = $this->getUserinfo();
			if($info['is_top'] ==1){
				$map['m.s_uid'] = session('user_auth.uid');
			}else{
				$map['m.uid'] = session('user_auth.uid');
			}
		}		
		//$map['m.username|m.nickname'] = array('like', '%' . (string) $nickname . '%');
		$order = "m.uid desc";

		$list  = db('member')->alias('m')->join('cps_member_extend e','e.uid = m.uid')->where($map)->order($order)->paginate(30,false,['type'=> 'page\Page', 'query' => ['keyword'=>input('keyword')]]);
		$statistics = model('Statistics');
		$dataSection = $statistics->dataSection();

		//获取上上个月时间
        $beforelast['Start'] =mktime(0, 0, 0, date('m') - 2, 1, date('Y'));
        $beforelast['End'] =mktime(23, 59, 59, date('m') - 2, date('t', $beforelast['Start']), date('Y'));

        //日期处理
        $today = date('Y-m-d',time());
        $yestoday = date('Y-m-d',strtotime("-1day"));
        $time_today = strtotime($today);
        $time_yestoday = strtotime($yestoday);
        //日期处理结束
        //var_dump($time_today);
        //var_dump($time_yestoday);

        $today_all_user = db('order')->where('status','=',1)->where('create_time','>=',$time_today)->sum('money');
        if(!$today_all_user){
            $today_all_user = 0 ;
        }

        //统计所有下线(排除没有渠道新用户)
        $mk =  db('wxmp')->field('id')->where('uid',session('user_auth.uid'))->select();
        $array = array_column($mk, 'id');
        $strs = implode(",",$array);

        //新增用户充值
        //$today_new_user = db('order')->where('user_reg_time','>=',$time_today)->where('create_time','>=',$time_today)->where('status','=',1)->sum('money');
        $today_new_user = db('order')->where('user_reg_time','>=',$time_today)->where('create_time','>=',$time_today)->where('status','=',1)->where('agentid','in',$strs)->sum('money');
        if(!$today_new_user){
            $today_new_user = 0 ;
        }
        // var_dump($today_all_user);exit;
        //var_dump($today_new_user);

        if($list){
			foreach($list->all() as $key =>$val ){
				//结算单总额
				$balmoney = db('pay_balance')->where(['uid'=>$val["uid"]])->sum('balmoney');
				//未提现总额
				$yesterday = mktime(0,0,0,date('m'),date('d')-1,date('Y'));
				$wmoney = db('pay_balance')->where(['status'=>0,'uid'=>$val["uid"]])->where('create_time <= '.$yesterday)->sum('balmoney');
                //今日新用户收入
                $income_today = db('order')
				->whereTime('create_time','>=', $time_today)
				->whereTime('user_reg_time','>=', $time_today)
				->where('agentid','=',$val["uid"])
				->where('status','=',1)
				->sum('money');

                //昨日新用户收入
                $income_yestoday = db('order')
				->whereTime('create_time','between',[$time_yestoday, $time_today])
				->whereTime('user_reg_time','between',[$time_yestoday, $time_today])
				->where('agentid','=',$val["uid"])
				->where('status','=',1)
				->sum('money');


				$list->offsetSet($key, array_merge($val, [
					'todayPay'=>$statistics->paySum($val["wxmpid"],1,1,0,$dataSection["today"]["Start"],$dataSection["today"]["End"],0,0,0,$val["uid"]),
					'yesterdayPay'=>$statistics->paySum($val["wxmpid"],1,1,0,$dataSection["yesterday"]["Start"],$dataSection["yesterday"]["End"],0,0,0,$val["uid"]),
					'allPay'=>$statistics->paySum($val["wxmpid"],1,1,0,0,0,0,0,0,$val["uid"]),
                    'monthPay'=>$statistics->paySum($val["wxmpid"],1,1,0,$dataSection["month"]["Start"],$dataSection["month"]["End"],0,0,0,$val["uid"]),
                    'lastmonth'=>$statistics->paySum($val["wxmpid"],1,1,0,$dataSection["prevmonth"]["Start"],$dataSection["prevmonth"]["End"],0,0,0,$val["uid"]),
                    'beforelast'=>$statistics->paySum($val["wxmpid"],1,1,0,$beforelast['Start'],$beforelast['End'],0,0,0,$val["uid"]),
                    //结算单总额
					'balmoney'=>$balmoney?$balmoney:0,
					//未提现总额
					'wmoney'=>$wmoney?$wmoney:0,
                    'income_today' =>$income_today,
                    'income_yestoday' =>$income_yestoday,
                    //'yesterdayPay' => $yesterdayPay,
				]));
			}
		}

		//登录用户的用户组id
		$group = session('user_auth.group');

		$data = array(
			'list' => $list,
			'page' => $list->render(),
            'group'=>$group,
            'keyword' =>input('keyword'),
            'today_all_user' => $today_all_user,
            'today_new_user' => $today_new_user
		);
		
		$this->assign($data);
		$this->assign('level',$level);
		$this->setMeta("下线管理");
		return $this->fetch();
	}

	public function addagent() {
		$model = \think\Loader::model('User');
		if (IS_POST) {
			$data = $this->request->param();
			
			//创建注册用户
			$result = $model->register($data['username'], $data['password'], $data['repassword'], $data['email'], false);
			if ($result) {
				return $this->success('用户添加成功！', url('admin/user/agent'));
			} else {
				return $this->error($model->getError());
			}
		} else {
			$info = $this->getUserinfo();
			$data = array(
				'keyList' => $model->addfield,
				'info'=>$info,
			);
			$this->assign($data);
			$this->setMeta("添加代理");
			return $this->fetch();
		}
	}

	public function groups() {
		$group = db('AuthGroup')->where("status","1")->column('id,title');
		$group[99] = "普通用户";
		$group[999] = "管理员";
		return $group;
	}
	
	public function autologin() {
		$uid      = input('id');
		$model = \think\Loader::model('User');
		$user = db('member')->where('uid',$uid)->find();
		$model->autoLogin($user);
		return $this->success("登录成功！", url('admin/index/index'));
	}

}